package com.i77studio.springbootdemo;

import com.i77studio.entity.User;
import com.i77studio.exceptions.UserIdMismatchException;
import com.i77studio.exceptions.UserNotFoundException;
import com.i77studio.mapper.UserMapper;
import jakarta.annotation.Resource;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * {@code: @Author:} Guo XiongHui
 * {@code: @Date:} 2024/12/27 13:21
 **/

@RestController
@RequestMapping("/api/users")
public class UserController {
    @Resource
    private UserMapper userMapper;

    @GetMapping("/max_id")
    public int getCurrentMaxId() {
        Integer max_id = userMapper.getCurrentMaxId();
        return max_id;
    }

    @GetMapping
    public List<User> findAll() {

        return userMapper.selectAll();
    }

    @GetMapping("/{id}")
    public User findOne(@PathVariable Long id) throws UserNotFoundException {
        Integer nId = Math.toIntExact(id);
        User user = userMapper.selectById(nId);
        if (user == null) {
            throw new UserNotFoundException();
        }
        return user;
    }

    @GetMapping("/username/{username}")
    public List<User> findByUserName(@PathVariable String username) throws UserNotFoundException {
        List<User> users = userMapper.selectByUserName(username);
        if (users.size() == 0) {
            throw new UserNotFoundException();
        }
        return users;
    }

    @PostMapping
    @ResponseStatus(HttpStatus.CREATED)
    public User create(@RequestBody User user) {
        int ret = userMapper.insert(user);
        return user;
    }

    @DeleteMapping("/{id}")
    public void delete(@PathVariable Long id) throws UserNotFoundException {
        Integer nId = Math.toIntExact(id);
        User user = userMapper.selectById(nId);
        if (user == null) {
            throw new UserNotFoundException();
        }
        int ret = userMapper.deleteById(nId);
    }

    @PutMapping("/{id}")
    public User updateUser(@RequestBody User user, @PathVariable Long id)
            throws UserNotFoundException, UserIdMismatchException {
        Integer nId = Math.toIntExact(id);
        if (!user.getId().equals(nId)) {
            throw new UserIdMismatchException();
        }
        User userF = userMapper.selectById(nId);
        if (userF == null) {
            throw new UserNotFoundException();
        }
        int ret = userMapper.updateById(user);
        return user;
    }
}
